import {createSlice, PayloadAction} from "@reduxjs/toolkit";

import {Part} from "type/Part";
import {StateBaseType} from "redux/StateBaseType";
import {ReduxStatus} from "enum/ReduxStatus";
import {
    fetchAddPart,
    fetchDeletePart,
    fetchFuzzyPart,
    fetchPageData,
    fetchPartGroup, fetchPartProvider,
    fetchUpdatePart
} from "./async/partAsyncAction";
import LogFactory from "log/LogFactory";
import DrpSettingHandler from "component/drp/DrpSettingHandler";
import {compareObjectMergeProps} from "util/compare";
import {PartGroup} from "type/PartGroup";
import PartDataConvert from "convert/PartDataConvert";
import {PartProvider} from "type/PartProvider";

const log = LogFactory.getLog("PartReducer") ;

/**
 * 零件信息Redux状态类型声明
 */
export type PartState = StateBaseType<Part> & {
    /**
     * 是否模糊查询
     */
    isFuzzy: boolean ,
    /**
     * 是零件组数据准备就绪状态
     */
    groupReady: boolean ,
    /**
     * 零件供应商数据准备就绪状态
     */
    providerReady: boolean ,
    /**
     * 零件组数据
     */
    partGroupData: PartGroup[] ,
    /**
     * 零件供应商数据
     */
    partProviderData: PartProvider[] ,
}
// redux 状态初始化
const initialState: PartState = {
    data: [],
    loading: false,
    total: 0,
    current: 1,
    pageSize: DrpSettingHandler.getInstance().getConfig().partPageSize,
    status: ReduxStatus.INIT,
    isFuzzy: false,
    groupReady: false,
    partGroupData: [],
    providerReady: false,
    partProviderData: [],
};

// 创建reducer数据片
export const partReducer = createSlice({
    name: "part",
    initialState,
    reducers: {
        /**
         * 修改零件库存
         * @param action partId: 零件ID , inventory: 库存数量
         */
        updatePartInventory: (state, action: PayloadAction<{partId: number , inventory: number}>) => {
            let index = state.data.findIndex(item => item.id === action.payload.partId) ;
            if (index === -1){
                log.warn("修改零件库存失败,没有找到对应的零件信息") ;
                return ;
            }
            state.data[index].repertorySize = action.payload.inventory ;
        }
    } ,
    extraReducers: (builder) => {
        builder.addCase(fetchPageData.pending, (state) => {
            state.loading = true;
            state.status = ReduxStatus.PENDING;
        });
        builder.addCase(fetchPageData.fulfilled, (state, action) => {
            if (action.payload === null) {
                state.loading = false;
                state.status = ReduxStatus.FAILED;
                return;
            }
            const dataConvert = new PartDataConvert(action.payload.data) ;
            state.groupReady && dataConvert.setPartGroupData(state.partGroupData) ;
            state.providerReady && dataConvert.setPartProviderData(state.partProviderData) ;
            dataConvert.convert() ;
            state.loading = false;
            state.status = ReduxStatus.SUCCESS;
            state.data = action.payload.data;
            state.pageSize = action.payload.pageSize;
            state.current = action.payload.currentPage;
            state.total = action.payload.total;
        });

        builder.addCase(fetchAddPart.fulfilled, (state, action) => {
            if (action.payload.success){
                state.status = ReduxStatus.REFRESH;
            }
        });

        builder.addCase(fetchUpdatePart.fulfilled, (state, action) => {
            if (action.payload == null){
                return;
            }
            let index = state.data.findIndex(item => item.id === action.payload?.id) ;
            if (index === -1){
                log.warn("修改零件信息失败,没有找到对应的零件信息") ;
                return ;
            }
            log.redux("更新零件信息成功",action.payload) ;
            // 处理具体业务
            compareObjectMergeProps(state.data[index],action.payload) ;
        });

        builder.addCase(fetchDeletePart.fulfilled, (state, action) => {
            if (action.payload === void 0){
                log.warn("删除失败") ;
                return ;
            }
            let index = state.data.findIndex(item => item.id === action.payload) ;
            if (index === -1){
                log.redux("删除零件信息失败,没有找到对应的零件信息") ;
                return ;
            }
            state.data.splice(index,1) ;
        });

        builder.addCase(fetchFuzzyPart.fulfilled, (state, action) => {
            if (action.payload === null) {
                state.status = ReduxStatus.FAILED;
                return;
            }
            state.status = ReduxStatus.SUCCESS;
            state.data = action.payload;
            state.total = action.payload.length ;
            state.pageSize = action.payload.length ;
            state.current = 1 ;
        });

        builder.addCase(fetchPartGroup.fulfilled, (state, action) => {
           if (action.payload.success){
               state.groupReady = true ;
               state.partGroupData = action.payload.data ;
           }
        });

        builder.addCase(fetchPartProvider.fulfilled, (state, action) => {
            if (action.payload.success){
                state.providerReady = true ;
                state.partProviderData = action.payload.data ;
            }
        });
    }
});

export const {updatePartInventory} = partReducer.actions ;
export default partReducer.reducer ;
